package com.xwd.dao.impl;

import com.xwd.dao.BookDao;
import com.xwd.pojo.Book;
import com.xwd.utils.ConnectionPool;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName BookDaoImpl
 * @Description: com.xwd.dao.impl
 * @Auther: xiwd
 * @Date: 2022/2/13 - 02 - 13 - 13:11
 * @version: 1.0
 */
public class BookDaoImpl implements BookDao {
    @Override
    public Long findTotalSize(String sql, Object ...args) {
        QueryRunner queryRunner=new QueryRunner();
        //获取Connection对象
        Connection connection = ConnectionPool.popConnection();
        Long queryRows=0L;
        //查询操作
        try {
            queryRows = queryRunner.query(connection, sql ,args,new ScalarHandler<Long>());
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.pushConnection(connection);
        }
        return queryRows;
    }

    //methods
    @Override
    public List<Book> queryList(String sql, Object... args) {
        QueryRunner runner=new QueryRunner();
        //获取Connection对象
        Connection connection = ConnectionPool.popConnection();
        //执行sql语句
        List<Book> books = null;
        try {
            books = runner.query(connection, sql, args, new BeanListHandler<Book>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.pushConnection(connection);
        }
        return books;
    }

}
